package com.wy.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * description TokenGlobalFilter
 * author wy
 * date 2021-09-05 23:14
 **/
@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered
{

//    @Autowired
//    private UserFeignClient userFeignClient;

    /**
     * 进⾏token的验证，⽤户微服务和验证码微服务的请求不过滤（⽹关调⽤下游⽤户微服务的token验证接⼝）
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        // 用户微服务和验证码微服务的请求不过滤
        if (path.startsWith("/user") || path.startsWith("/code")) {
            return chain.filter(exchange);
        }
        // 获取Cookie，token不存在或者用户微服务查询不到重定向到登录页面
        List<HttpCookie> token = request.getCookies().get("token");
        if((token == null) || (token.size() == 0)) {
            String data = "No Token! Request be denied!";
            DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
//        if (!CollectionUtils.isEmpty(cookies)) {
//            HttpCookie cookie = cookies.get(0);
//            String token = cookie.getValue();
//            if (!"".equals(userFeignClient.getEmail(token))) {
//                return chain.filter(exchange);
//            }
//        }
        // 返回状态码 303，重定向到登录页面
        response.getHeaders().set(HttpHeaders.LOCATION, "/static/login.html");
        response.setStatusCode(HttpStatus.SEE_OTHER);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
